var SmartTable1 = {
	isLoad: false,
	getHtml: function(ele) {
		var path = SmartTable1.path;
		var target = $(ele);
		$.get(path + 'model.html', function(html) {
			var dbProcs = SmartTable1.dbProcs;
			var $html = $(html);
			var $funGroupId = $html.find('#funGroupId');
			var $funsId = $html.find('#funsId');
			var $funBackType = $html.find('#funBackType');
			var $funDisc = $html.find('#funDisc');
			var $selectType = $html.find('input[name="selectType"]');
			var $funArea = $html.find('#funArea');
			var $sqlArea = $html.find('#sqlArea');

			var i = 0;
			for (var dbGroups in dbProcs) {
				var procs = dbProcs[dbGroups];

				var groupId = dbGroups.split('-')[0];
				var groupName = dbGroups.split('-')[1];

				var $option = $('<option value="' + groupId + '">' + groupName + '</option>').data('data', procs);
				$funGroupId.append($option);
				if (i == 0) {
					pullFuns(procs);
				}

				i++;
			}

			function pullFuns(procs) {
				$funsId.children().remove();
				for (var y = 0; y < procs.length; y++) {
					var proc = procs[y];
					var $option = $('<option value="' + proc.funname + '">' + proc.funname + '</option>').data('data', proc);
					$funsId.append($option);

					if (y == 0) {
						pullTxt(proc);
						showParams();
					}
				}
			}
			// 填充返回类型、函数描述等内容,并根据参数判断是否显示参数配置
			function pullTxt(proc) {
				SmartTable1.fouceProc = proc;
				var backTypeName = proc.backName;
				var funDesic = proc.fundesic;
				$funBackType.text(backTypeName);
				$funDisc.text(funDesic);
			}

			function showParams() {
				var proc = SmartTable1.fouceProc;
				var params
				try {
					params = eval(proc.funparams);
				} catch (e) {
					params = [];
				}
				var $funParamTableBody = $html.find('#funParamTableBody');
				var $paramsArea = $html.find('#paramsArea');

				$funParamTableBody.children().remove();
				if (params.length > 0) {
					$paramsArea.show();
					for (var i = 0; i < params.length; i++) {
						var $tr = $('<tr></tr>')
						var p = params[i];
						var name = p.name;
						var useType = p.useType;

						var $tds = $('<td>' + name + '</td><td>' + useType + '</td><td><select class="my_select"><option>测试一</option><option>测试二</option><option>测试三</option></select></td>');
						$tr.append($tds);

						$funParamTableBody.append($tr);
					}
				} else {
					$paramsArea.hide();
				}
			}

			$funGroupId.on('change', function() {
				var procs = $(this.selectedOptions).data('data');
				pullFuns(procs);
			});
			$funsId.on('change', function() {
				var proc = $(this.selectedOptions).data('data');
				pullTxt(proc);
			});

			$selectType.on('click', function() {
				var v = this.value;
				if (v == 'sql') {
					$sqlArea.show();
					$funArea.hide();
				} else if (v == 'fun') {
					$sqlArea.hide();
					$funArea.show();
				}
			});
			target.html($html);
		});
	},
	preview: function(data) {
		var previewId = "#tabPreviewTable";
		$(previewId + ' table').remove();
		jQuery.jsontotable(data, {
			id: previewId,
			header: true,
			excel: true
		});
		$(previewId + ' table').addClass('stripe');
		var exportTableData = $(previewId + ' table').data('tableJson');
		return exportTableData;
	}
}

var smartTableOkSign = false;
CKEDITOR.plugins.add('smarttable', {
	icons: 'smarttable',
	requires: 'widget',
	init: function(editor) {
		// 加载函数列表
		// $.get('table/getDbProcs').success(function(data) {
		// 	SmartTable1.dbProcs = data;
		// });


		CKEDITOR.dialog.add('smarttable', this.path + 'dialogs/smarttable.js');
		SmartTable1.path = this.path;

		var cls = 'smarttable-preview';

		function appendTable(target, code, tabWidth, tabId) {
			var contentArea = target.findOne('.simplebox-content');
			if (contentArea.getChildCount() != 0) {
				for (var i = 0; i <= contentArea.getChildCount(); i++) {
					var node = contentArea.getChild(0);
					node.remove();
				}
			}

			var obj = $_doc.data(tabId);

			function doSome(data) {
				$.jsontotable(data, {
					id: "#" + tempTableArea,
					header: true
				});

				if (!obj) {
					obj = {
						data: data,
						exportTableData: $('#' + tempTableArea + ' table').data('tableJson')
					}
					$_doc.data(tabId, obj);
				}
				var tableArea = $('#' + tempTableArea);
				var table = tableArea.children().attr('id', tabId);
				table.addClass('stripe');
				table.css('font-size', '12px;');
				table.css('line-height', '1.5;');
				table.css('height', tabWidth + 'px');

				contentArea.appendHtml(table[0].outerHTML);
				ck.util.builTableData(tabId, tabWidth, editor.document.$);
				tableArea.children().remove();
			}

			if (obj) {
				setTimeout(function() {
					doSome(obj.data);
				}, 50);
			} else {
				ck.util.sendAjax({
					url: 'table/getTable',
					data: {
						pageId: pageId,
						code: code
					}
				}, doSome);
			}
		}

		editor.widgets.add('smarttable', {
			button: '插入表格',
			dialog: 'smarttable',
			draggable: false,
			requiredContent: 'div(simplebox)',
			template: '<div class="simplebox ' + cls + '"><div class="simplebox-content"></div></div>',
			init: function() {
				this.once('ready', function() {
					if (this.data.isLoad == 1) {
						var code = this.data.code,
							// dsName = this.data.dsName,
							tabWidth = this.data.tabWidth,
							tabId = this.data.tabId;

						appendTable(this.element, code, tabWidth, tabId)

						// 设置为0，避免 ctrl+z 会再次执行
						this.setData('isLoad', 0);
					}
				});
				var element = this.element;
				$(element.$).hover(jQuery.fn.widgetMouseOver, jQuery.fn.widgetMouseOut).onPositionChanged(jQuery.fn.showIcon);				
			},
			upcast: function(el, data) {
				if (el.name == 'div' && el.hasClass(cls)) {
					var attr = el.attributes;

					data.code = attr['data-code'];
					data.tabWidth = attr['data-tabwidth']; // 这里大写会被转换成小写
					data.tabId = attr['data-tabid'];

					// 标记此元素为页面加载的元素
					data.isLoad = 1;

					return el;
				}
			},
			data: function() {
				if (smartTableOkSign) {
					smartTableOkSign = false;

					var element = this.element;

					var code = this.data.code,
						// dsName = this.data.dsName,
						tabWidth = this.data.tabWidth,
						// tabId = "tabId_" + new Date().valueOf();
						tabId = SmartTable1.tabId;

					element.data('code', code);
					element.data('tabwidth', tabWidth);
					element.data('tabid', tabId);

					appendTable(element, code, tabWidth, tabId);
				}
			}
		});
	}
});